﻿using AngleSharp.Dom;
using AngleSharp.Parser.Html;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BaseEpub
{
    /// <summary>
    /// 南大出版社
    /// </summary>
    public class NdPressPageHtml:IPageHtmlBase
    {
        public string GetContent(string content)
        {
            HtmlParser parser = new HtmlParser();
            GetImageTool imgTool = new GetImageTool();
            //获取正文里的正文dom
            //<img src="../Images/gs020.jpg" class="inline-image2"/></p>
            var doc = parser.Parse(content);
            IEnumerable<IElement> imgEleList = doc.QuerySelectorAll("img"); //Distinct去掉重复的图片数据
            if (imgEleList != null && imgEleList.Count() > 0)
            {
                //判断图片路径是否已经存在，存在就不再导入
                string isExistSrc = "";
                foreach (IElement imgEle in imgEleList)
                {
                    string src = imgEle.GetAttribute("src");
                    if (!string.IsNullOrEmpty(isExistSrc) && src == isExistSrc)
                    {
                        continue;
                    }
                    isExistSrc = src;

                    string[] srcStr = src.Split('/');
                    string imgPath = @"E:\MyCode\NetCode\AngleSharpDemo\有机化学样本3\有机化学样本3\OEBPS\" + srcStr[1] + @"\" + srcStr[2];

                    //byte[] imgBytes = GetByte(imgPath);
                    //string imgType = ImageTypeCheck.CheckImageTypeName(imgPath);
                    //string result = SaveImage(imgBytes, imgType);

                    //BaseEpub.ReplacePageImg.UpLoadBack upLoadBack = JsonConvert.DeserializeObject<BaseEpub.ReplacePageImg.UpLoadBack>(result);
                    ////图片id
                    Int64 imgId = imgTool.GetImgId(imgPath);
                    
                    //替换为hexstudy的web路径
                    string newSrc = @"http://cms.ld.hexstudy.com/FileManage/DownLoadImage?id=" + imgId;
                    content = content.Replace(src, newSrc);
                }
            }
            return content;
        }
    }
}
